<!-- Author: Edwin -->
<template>
  <el-dialog :visible.sync="showDialog"
             :close-on-press-escape="false"
             :close-on-click-modal="false"
             append-to-body
             destroy-on-close
             top='17vh'
             class="block-model-dialog"
             width="1030px">
      <div slot="title">
        <div class="title">
          {{ blockInfo.name }}
        </div>
      </div>
    <div v-if="loading" v-loading="loading" style="height:668px">

    </div>
      <el-card shadow="never">
        <template v-if="isPermission">
          <template v-if="hasLayout">
            <ScriptRender v-if="dialogVisible"
                          ref="script-render"
                          :blockInfo='blockInfo'
                          @transmitFilterSqlRes="filterSqlForm"
                          @hiddenSettingModel="hiddenSettingModels"
                          @test="changeBot"
                          :showJson='layoutScriptJson'
                          :psa='psa'
                          :dataForm='dataForm'>
              <template v-slot:layout>
                <ScriptRender v-if="dialogVisible"
                              ref="script-render"
                              :blockInfo='blockInfo'
                              @transmitFilterSqlRes="filterSqlForm"
                              @hiddenSettingModel="hiddenSettingModels"
                              @test="changeBot"
                              :showJson='noLayoutScriptJson'
                              :psa='psa'
                              :dataForm='dataForm'></ScriptRender>
              </template>
            </ScriptRender>
          </template>
          <template v-else>
            <ScriptRender v-if="dialogVisible"
                          ref="script-render"
                          :blockInfo='blockInfo'
                          @hiddenSettingModel="hiddenSettingModels"
                          @transmitFilterSqlRes="filterSqlForm"
                          @test="changeBot"
                          :showJson='scriptJson'
                          :psa='psa'
                          :dataForm='dataForm'></ScriptRender>
          </template>
        </template>
        <div v-else style="padding-top: 15px">You do not have permission to edit this block, please contact MSPbots support for help.</div>

      </el-card>
      <div slot="footer"
            class="dialog-footer">
        <el-button type="primary"
                  v-if="onlyHasOneLine && !isFirstBlock()"
                  @click="previousSettingModel"
                  plain
                  size="mini">Previous</el-button>
        <el-button @click="saveDataForm"
                  v-if="(onlyHasOneLine && isLastBlock()) || !onlyHasOneLine"
                  size="mini">{{$t('custom.bots.edit.finish')}}</el-button>
        <el-button type="primary"
                  v-if="onlyHasOneLine && !isLastBlock()"
                  @click="nextSettingModel"
                  plain
                  size="mini">Next</el-button>
      </div>
  </el-dialog>
</template>

<script>
import ScriptRender from '@/components/script-render/index'
import { generalConvertJsonToSQL } from '@/utils/common'
import {  fetchSoftwareSetting } from '@/api/new'

export default {
  components: { ScriptRender },
  inject :{
    scriptList:{
      default:()=>[]
    },
    blockDataSource:{
      default:()=>[]
    },
    botScriptList:{
      default:()=>[]
    },
    botInfo:{
      default:()=>{}
    },
  },
  data () {
    return {
      dialogVisible: false,
      blockInfo: {},
      scriptJson: [],
      dataForm: {},
      loading: false,
      psa:''
    }
  },
  computed: {
    isPermission () {
      return this.blocksList.filter(item => item.id === this.blockInfo.blockId).length
    },
    blocksList () {
      return this.scriptList()
    },
    hasLayout () {
      return this.scriptJson.some(e => e.type === 'layout')
    },
    layoutScriptJson () {
      return this.scriptJson.filter(e => e.type === 'layout')
    },
    noLayoutScriptJson () {
      return this.scriptJson.filter(e => e.type !== 'layout')
    },
    hasCycletemplatemultiple () {
      return this.scriptJson.some(e => e.type === 'cycle-multiple-template')
    },
    cycleScriptJson () {
      return this.scriptJson.filter(e => e.type === 'cycle-multiple-template')
    },
    noCycleScriptJson () {
      return this.scriptJson.filter(e => e.type !== 'cycle-multiple-template' && e.type !== 'layout' && e.type !== 'template-multiple')
    },
    cycleContentScriptJson () {
      return this.scriptJson.filter(e => e.type === 'template-multiple')
    },
    isCycletemplatemultiple () {
      return false
    },
    nowPageName () {
      return this.$store.state.contentTabsActiveName
    },
    showDialog: {
      get () {
        return Boolean(this.dialogVisible)
      },
      set (val) {
        this.dialogVisible = val
      }
    },
    onlyHasOneLine () {
      let hasOneLine = true
      let dataSource = this.blockDataSource() || []
      for (let i = 0; i < dataSource.length; i++) {
        if (dataSource.filter(e => e.pid === dataSource[i].id).length > 1) {
          hasOneLine = false
        }
      }
      return hasOneLine
    }
  },
  watch: {
    dialogVisible (val) {
      if (!val) {
        Object.assign(this.$data, this.$options.data())
      }
    }
  },
  methods: {
    changeBot (val) {
      this.dataForm = val
    },
    hiddenSettingModels () {
      this.saveDataForm()
      this.dialogVisible = false
    },
    open (blockInfo, e) {
      this.dialogVisible = true
      this.blockInfo = blockInfo
      this.init()
      this.getSoftwareSetting()
    },
    init () {
      try {
        this.scriptJson = this.blocksList.find(e => e.id === this.blockInfo.blockId).paramsJson.fields
      } catch (error) {
        this.scriptJson = []
      }
      this.dataForm = this.getSavedDataForm() ? this.getSavedDataForm() : this.getDefaultDataForm(this.scriptJson)
    },
    async getSoftwareSetting () {
      try {
           const { data: response } = await fetchSoftwareSetting()
           if (response.code !== 0) {
             throw response.msg
           }
           if (response&&response.data&&response.data.software&&response.data.software.selectedPSA&&response.data.software.selectedPSA[0]) {
            this.psa = response.data.software.selectedPSA[0]
           }
      } catch (error) {
        
      }

      
    },
    otherValidateRules () {
      try {
        return this.$refs['script-render'].toAddressDataValidate() && this.$refs['script-render'].templateMultipleDataValidate() && this.$refs['script-render'].fliterDataValidate('fromBot')
      } catch (e) {
        return false
      }
    },
    validateRules () {
      return this.$refs['script-render'].validateRules()
    },
    checkDataFilter () {
      try {
        return this.$refs['script-render'].checkDataFilter()
      } catch (e) {
        return true
      }
    },
    compatibilityForTriggerFilter (data) {
      let filterIndex = this.scriptJson.findIndex(e => e.type === 'filter')
      // Is Trigger script
      if (this.hasLayout && filterIndex > -1) {
        let temp = this._.cloneDeep(data)
        temp[this.scriptJson[filterIndex].sqlText] = generalConvertJsonToSQL(data[this.scriptJson[filterIndex].text])
        return temp
      } else {
        return data
      }
    },
    getSavedDataForm () {
      let oldList = this.botScriptList()
      let nowBlockIndex = oldList.findIndex(e => e.trackId === this.blockInfo.selfTrackId)
      if (nowBlockIndex === -1) {
        return false
      } else {
        let temp = this._.cloneDeep(oldList[nowBlockIndex].paramsValue)
        return temp
      }
    },
    getDefaultDataForm (itemJson) {
      if (!Array.isArray(itemJson)) {
        return {}
      }
      let temp = {}
      for (let i = 0; i < itemJson.length; i++) {
        const element = itemJson[i]
        if (typeof element.defaultValue === 'object') {
          temp[element.text] = JSON.parse(JSON.stringify(element.defaultValue))
        } else {
          temp[element.text] = element.defaultValue
        }
      }
      return temp
    },
    getKeyArrayList (paramsvaluesend) {
      let type = ''
      let id = ''
      this.scriptJson.forEach(item => {
        if (item.type === 'radio-select' && paramsvaluesend[item.text]) {
          type = paramsvaluesend[item.text][item.radioValue]
          id = paramsvaluesend[item.text][item.selectValue]
        }
      })
      if (!type) {
        return false
      }
      const params = {}
      type === 'dataset' && (params['datasetId'] = id)
      type === 'widget' && (params['gadgetId'] = id)
      this.$interface.reports.getFieldsListApi(params)
        .then(({ data: res }) => {
          if (res.code !== 0) {
            this.setFilterKeyList([])
            return false
          }
          let temp = []
          res.data.forEach(item => {
            temp.push({
              label: item.name,
              value: item.name,
              type: item.type
            })
          })
          this.setFilterKeyList(temp)
        })
        .catch(() => { })
    },
    setFilterKeyList (list) {
      this.scriptJson.forEach(item => {
        if (item.type === 'filter') {
          item[item.keyOptions] = list
        }
      })
    },
    filterSqlForm () {
      this.$store.commit('FILTERSQL', this.dataForm.filters)
    },
    checkAndValidate () {
      if (!this.otherValidateRules()) {
        return false
      }
      if (!this.checkDataFilter()) {
        return false
      }
      return this.validateRules()
    },
    saveDataForm () {
      this.dataMapping()
      this.dialogVisible = false
    },
    changeModelAndSaveDataForm (blockId) {
      this.dataMapping()
      this.changeSettingModel(blockId)
    },
    previousSettingModel () {
      try {
        let dataSource = this.blockDataSource() || []
        let blockId = dataSource.find(e => e.id === this.blockInfo.pid).id
        this.changeModelAndSaveDataForm(blockId)
      } catch (error) { }
    },
    nextSettingModel () {
      try {
        let dataSource = this.blockDataSource() || []
        let blockIdList = dataSource.filter(e => e.pid === this.blockInfo.id)
        this.changeModelAndSaveDataForm(blockIdList[0].id)
      } catch (error) { }
    },
    dataMapping () {
      let temp = this.compatibilityForTriggerFilter(this.dataForm)
      let list = this.botScriptList()
      let nowBlockIndex = list.findIndex(e => e.trackId === this.blockInfo.selfTrackId)
      if (nowBlockIndex === -1) {
        let dataSource = this.blockDataSource() || []
        let parentNodeIndex = dataSource.findIndex(e => e.id === this.blockInfo.pid)
        list.push({
          botId: this.botInfo().id,
          scriptId: this.blockInfo.blockId,
          paramsValue: null,
          triggerId: parentNodeIndex > -1 ? dataSource[parentNodeIndex].selfTrackId : this.botInfo().id,
          trackId: this.blockInfo.selfTrackId,
          name: this.blockInfo.name
        })
      }
      let data = list.map(e => {
        if (e.trackId === this.blockInfo.selfTrackId) {
          e.paramsValue = temp
        }
        return e
      })
      this.$emit('setScriptList', data)
    },
    changeSettingModel (blockId) {
      let dataSource = this.blockDataSource() || []
      this.blockInfo = dataSource.find(e => e.id === blockId)
      this.$nextTick(() => { this.init() })
    },
    isFirstBlock () {
      let dataSource = this.blockDataSource() || []
      return Boolean(dataSource.findIndex(e => e.id === this.blockInfo.pid) === -1)
    },
    isLastBlock () {
      let dataSource = this.blockDataSource() || []
      return Boolean(dataSource.findIndex(e => e.pid === this.blockInfo.id) === -1)
    }
  }
}
</script>

<style scoped lang='scss'>
.block-model-dialog {
  ::v-deep .el-dialog__body {
    box-shadow: 0px -1px 0px 0px #f0f0f0;
  }
  ::v-deep .el-dialog__header {
    padding: 20px;
  }
}
.title {
  font-weight: bold;
  font-size: 1.2em;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}
.description {
  padding-bottom: 20px;
}
.el-card {
  border: 0;
}
::v-deep .el-card__body {
  padding: 0 !important;
}
::v-deep .el-dialog__body {
  padding-top: 0;
}
</style>
